package com.rc.saas.mini.controller.tenant;


import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.config.UpYunConfig;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.tenant.TenantAppInfo;
import com.rc.saas.mini.model.tenant.TenantAppUpgrade;
import com.rc.saas.mini.model.tenant.TenantOpenService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.tenant.TenantAppInfoService;
import com.rc.saas.mini.service.tenant.TenantAppUpgradeService;
import com.rc.saas.mini.service.tenant.TenantOpenServiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP版本信息
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/app")
@Api(tags = "28.APP功能")
public class TenantAppController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(TenantAppController.class);

    @Autowired
    private TenantAppInfoService tenantAppInfoService;
    @Autowired
    private TenantAppUpgradeService tenantAppUpgradeService;
    @Autowired
    private MemberInfoService memberInfoService;
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private TenantOpenServiceService tenantOpenServiceService;
    @Autowired
    private UpYunConfig upYunConfig;


    /**
     * 取最新版本
     *
     * @param osType
     * @return
     */
    @RequestMapping(value = "checkVersion", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "取版本信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "osType", paramType = "query", value = "0，1 APP手机操作系统: 应用类型 " +
                    "0 IOS，1Android", required = true)})
    public DataTResponse<TenantAppInfo> checkVersion(HttpServletRequest request, String osType) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        logger.info("controller request,:{}", osType);
        if (osType == null) {
            osType = "1";
        }
        TenantAppInfo tenantApp = tenantAppInfoService.checkVersion(osType, tenantCode);

        return DataTResponse.SUCCESS_DATA(tenantApp);
    }

    /**
     * 是否有新版本部署
     *
     * @param currentVersion
     * @param version
     * @return
     */
    private int compareUpdateVersion(String currentVersion, TenantAppInfo version) {
        if (StringUtils.isBlank(currentVersion)) {
            logger.error("版本号currentVersion为空");
            return 0;
        }

        String[] versionStr = currentVersion.split("\\.");
        if (versionStr.length != 3) {
            logger.error("版本格式不正确versionId", currentVersion);
            return 0;
        }

        if (version == null || StringUtils.isBlank(version.getVersionName())) {
            logger.error("后台配置更新版本错误");
            return 0;
        }

        String[] sysVersionStr = version.getVersionName().split("\\.");
        if (sysVersionStr.length != 3) {
            logger.error("后台配置版本格式不正确versionId", version.getVersionName());
            return 0;
        }

        String TenantApp = currentVersion.replaceAll("\\.", "");
        String sysVersion = version.getVersionName().replaceAll("\\.", "");
        if (Integer.valueOf(TenantApp) < Integer.valueOf(sysVersion)) {
            return 1;
        }

        return 0;
    }


    ///**
    // * 获取下载地址
    // *
    // * @return
    // */
    //@RequestMapping("/getDownLoadUrl")
    //@ResponseBody
    //@ApiOperation(value = "获取下载地址", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //public DataTResponse<List<TenantAppInfo>> getDownLoadUrl(HttpServletRequest request, HttpServletResponse response) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return DataTResponse.FAIL("找不到对应运营商信息");
    //    }
    //    response.setHeader("Access-Control-Allow-Origin", "*");
    //    TenantAppInfo androidDownload = tenantAppInfoService.selectAndroidDownload(tenantCode);
    //    TenantAppInfo iosDownload = tenantAppInfoService.selectIosDownload(tenantCode);
    //    List<TenantAppInfo> TenantApps = new ArrayList<>();
    //    TenantApps.add(androidDownload);
    //    TenantApps.add(iosDownload);
    //    return DataTResponse.SUCCESS_DATA(TenantApps);
    //}


    ///**
    // * 获取下载版本历史
    // *
    // * @return
    // */
    //@RequestMapping("/listPageVersion")
    //@ResponseBody
    //@ApiOperation(value = "获取下载版本历史", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "pageNum", paramType = "query", value = "页码（默认1）", required = false),
    //        @ApiImplicitParam(name = "pageSize", paramType = "query", value = "页大小（默认10）", required = false),
    //        @ApiImplicitParam(name = "appType", paramType = "query", value = " '应用类型 0:IOS 1:ANDROID',", required = true)})
    //public DataTResponse<PageInfo<TenantAppUpgrade>> listPageVersion(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
    //                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, String appType) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return DataTResponse.FAIL("找不到对应运营商信息");
    //    }
    //
    //    PageInfo<TenantAppUpgrade> tenantAppUpgradePageInfo = tenantAppUpgradeService.listPageVersion(appType, tenantCode, pageNum, pageSize);
    //    return DataTResponse.SUCCESS_DATA(tenantAppUpgradePageInfo);
    //}
}
